package com.shcz.migu.presenter.base;

import android.content.Intent;
import android.util.Log;

import java.lang.ref.WeakReference;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;


public abstract class  BasePresenter<V>  {

    protected CompositeSubscription mCompositeSubscription;
    protected WeakReference<V> mViewRef; // view 的弱引用
    public void onCreate(){
        mCompositeSubscription = new CompositeSubscription();
    }

    public void onStart(){}//暂时没用到

    public void onStop(){}

    public void pause(){}//暂时没用到

    public void attachView(V view){
        mViewRef = new WeakReference<>(view);
    }

    public V getView() {
        return mViewRef != null ? mViewRef.get() : null;
    }

    public void detachView(){
        if (mViewRef != null){
            mViewRef.clear();
            mViewRef = null;
            Log.i("BasePresenter","已经GC...");
        }
    }

    public void attachIncomingIntent(Intent intent){}//暂时没用到

    public void onDestroy(){
        onUnsubscribe();
        detachView();
    }


    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }


    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

}
